package com.mao.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mao.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<com.mao.entity.User> wapper = new QueryWrapper<>();
        wapper.eq("username",username);
        com.mao.entity.User user = userMapper.selectOne(wapper);

        if (user == null ){
            throw new NullPointerException("不存在该用户");

        }

        List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_"+user.getUsername()+ ","+user.getUsername());
        return new User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),role);
    }


}
